package com.david.appletree

import android.app.Activity
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.Window
import android.view.WindowManager
import android.webkit.*
import android.widget.ImageView
import android.widget.ScrollView
import android.widget.TextView
import androidx.core.graphics.ColorUtils
import androidx.webkit.WebViewAssetLoader
import androidx.webkit.WebViewAssetLoader.AssetsPathHandler
import androidx.webkit.WebViewAssetLoader.ResourcesPathHandler
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.david.core.imgloader.LruImageLoader
import com.david.core.utils.MMKVUtil
import com.david.core.view.banner.KtBannerEntity
import com.david.core.view.banner.KtRecyclerBanner
import java.io.ByteArrayOutputStream
import java.io.File
import kotlin.math.roundToInt


class NewTestActivity:Activity() {
    private lateinit var title:TextView
    private val drawable = GradientDrawable().apply {
        shape = GradientDrawable.RECTANGLE
        colors = intArrayOf(
            Color.WHITE,
            ColorUtils.setAlphaComponent(Color.WHITE, (0xFF * 0.9f).toInt())
        )
        orientation = GradientDrawable.Orientation.TOP_BOTTOM
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        actionBar?.hide();// 隐藏ActionBar
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//remove notification bar  即全屏
//        WindowInsetsController
        setContentView(R.layout.activity_new_test)
        title = findViewById(R.id.title)
        title.background = drawable
        window.statusBarColor = Color.TRANSPARENT
        findViewById<ScrollView>(R.id.scroll).setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->


            if (scrollY < 0) {
                return@setOnScrollChangeListener
            }
            if (scrollY < 500) {
                Log.i("scroll", "scrollY:" + scrollY)
                drawable.apply {
                    alpha = (0xFF * (scrollY / 500f)).toInt()
                }
                window.statusBarColor = ColorUtils.setAlphaComponent(Color.WHITE, (0xFF * (scrollY / 500f)).roundToInt())


//                val alpha = MathUtils.clamp(
//                    scrollY.toFloat(),
//                    0f,
//                    500f
//                ) / 500f
//
//                val titleBgColor =
//                    ColorUtils.setAlphaComponent(Color.WHITE, (0xFF * (scrollY / 500f)).toInt())


            }
        }

//        compressTest()

//        testXmlParse()

//        testMmkv()
        title.setOnClickListener {
//                    testGlideDownload()
//            Log.e("mmkv", MMKVUtil.getInt("test").toString())x

//            testBig()
//            str += "拉"
//            testAutoSize()

            testPop()
        }
    }

    private fun testPop(){
//        ReaderMenuPop(this).showAtLocation(findViewById(android.R.id.content), Gravity.BOTTOM, 0, 0)
        ReaderMenuDialog(this).setCurrentPage(0).show()
    }

    var str = "测测"
    private fun testAutoSize(){
        val text: AutoSizeTextView = findViewById(R.id.test_text)
        text.setText(str)
    }

    private fun testBig(){
        LruImageLoader.getInstance().init(application)


        BigImgPop(this).showAtLocation(findViewById(android.R.id.content), Gravity.NO_GRAVITY, 0, 0)
    }

    private fun testCompressBitmap(){
        val optoins = BitmapFactory.Options()
//                    optoins.inSampleSize = 2
        optoins.inPreferredConfig = Bitmap.Config.RGB_565
        val bitmap = BitmapFactory.decodeResource(resources, R.drawable.share_bg, optoins)

        findViewById<ImageView>(R.id.test_img3).setImageBitmap(Bitmap.createBitmap(bitmap, 0, 0, 100, 100))
    }

    private fun testBanner(){
        LruImageLoader.getInstance().init(application)

        val banner:KtRecyclerBanner = findViewById(R.id.kt_banner)
        banner.setNavType(0)
        val datas = ArrayList<KtBannerEntity>()
        datas.add(object :KtBannerEntity{
            override val url: String?
                get() = "https://upload-images.jianshu.io/upload_images/17834800-b949afa746b41e12.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/300/h/240/format/webp"
        })
        datas.add(object :KtBannerEntity{
            override val url: String?
                get() = "https://upload-images.jianshu.io/upload_images/35375-f68933ac4308126b.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/300/h/240/format/webp"
        })
        banner.setDatas(datas)
    }

    private fun testRaw(){

    }

    private fun testGlideDownload(){


        Log.e("glide", "testGlideDownload")
        Glide.with(this)
            .downloadOnly()
            .load("https://ts1.cn.mm.bing.net/th?id=OIP-C.mH9YLFEL5YdVxJM82mjVJQHaEo&w=316&h=197&c=8&rs=1&qlt=90&o=6&dpr=2&pid=3.1&rm=2")
            .listener(object : RequestListener<File> {

                override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<File>, isFirstResource: Boolean): Boolean {
                    Log.e("glide", "onResourceReady")
                    return true

                }

                override fun onResourceReady(resource: File, model: Any, target: Target<File>?, dataSource: DataSource, isFirstResource: Boolean): Boolean {
                    Log.e("glide", "onResourceReady" + resource?.absolutePath + "   , uri:" + resource?.toURI())

                    val webview = findViewById<WebView>(R.id.webview)
                    webview.webChromeClient = WebChromeClient()
                    //                    webview.webViewClient = WebViewClient()

                    val assetLoader = WebViewAssetLoader.Builder()
                        .addPathHandler("/assets/", AssetsPathHandler(this@NewTestActivity))
                        .addPathHandler("/res/", ResourcesPathHandler(this@NewTestActivity))
                        .build()

                    webview.setWebViewClient(object : WebViewClient() {
                        override fun shouldInterceptRequest(
                            view: WebView?,
                            request: WebResourceRequest
                        ): WebResourceResponse? {
                            return assetLoader.shouldInterceptRequest(request.url)
                        }
                    })
                    // Assets are hosted under http(s)://appassets.androidplatform.net/assets/... .
                    // If the application's assets are in the "main/assets" folder this will read the file
                    // from "main/assets/www/index.html" and load it as if it were hosted on:
                    // https://appassets.androidplatform.net/assets/www/index.html
                    // Assets are hosted under http(s)://appassets.androidplatform.net/assets/... .
                    // If the application's assets are in the "main/assets" folder this will read the file
                    // from "main/assets/www/index.html" and load it as if it were hosted on:
                    // https://appassets.androidplatform.net/assets/www/index.html
                    //                    webview.loadUrl("https://appassets.androidplatform.net/assets/www/index.html")

                    val webSettings = webview.settings
                    //允许webview对文件的操作
                    //                    webSettings.setAllowUniversalAccessFromFileURLs(true);
                    webSettings.setAllowFileAccess(true);
                    //                    webSettings.setAllowFileAccessFromFileURLs(true);

                    webview.loadUrl("http://10.114.37.227:8090/files/test.html")
                    return true
                }

            })
            .preload();
    }

    var mWaveService = WaveService()


    private fun testIrRemote(){
//        val IR = getSystemService(CONSUMER_IR_SERVICE) as ConsumerIrManager

        //是否有红外模块
//        Log.i("test", "has irEmitter:${IR.hasIrEmitter()}")

//        手机有红外模块时直接发送
//        val pattern = intArrayOf(9000,4500, 560,560,    560,560,   560,560,   560,560,   560,560,   560,560,   560,560,   560,560,
//            560,1690,  560,1690,  560,1690,  560,1690, 560,1690, 565,1685, 560,1690, 560,1690,
//            560,1690,  560,560,  560,1690, 560,560, 560,560, 560,560, 560,1690,   560,560,
//            560,560 ,560,1690,  560,560,   560,1690, 560,1690, 560,1690,560,560, 560,1690
//            ,9000,2250,2250,94000  , 9000,2250,2250,94000)
//        IR.transmit(38000, pattern)//此方法控制手机产生 carrierFrequency为频率的，以pattern为红外开关的时间数组，发送红外信号。（例如：transmit(38000,{100,200,300,400})    将会产生一个频率为38KHz的红外信号，信号的电平高低为 100us高电平，200us低电平，300us高电平，400us低电平。注意pattern的数据个数要为偶数个，不然报错。）




//        通过音频接口发送音频数据给外接红外发射 设备
        mWaveService.sendSignal(0x00ff.toShort(), 0x1d00.toByte())
    }

    private fun compressTest(){
        val optoins = BitmapFactory.Options()
//                    optoins.inSampleSize = 2
        optoins.inPreferredConfig = Bitmap.Config.RGB_565

        val bitmap = BitmapFactory.decodeResource(resources, R.drawable.community_img_share_default, optoins)

        val bStream = ByteArrayOutputStream()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            bitmap.compress(Bitmap.CompressFormat.WEBP_LOSSLESS, 92, bStream)
        } else {
            bitmap.compress(Bitmap.CompressFormat.WEBP, 92, bStream)
        }
        findViewById<ImageView>(R.id.image).setImageBitmap(bitmap)
        Log.e("size", bStream.toByteArray().size.toString())
    }

    private fun testXmlParse(){
        val parse = HtmlSaxHelper()
        parse.parse()
        parse.persons
    }

    private fun testMmkv(){
        MMKVUtil.init(application)
        MMKVUtil.putInt("test", 1)
    }

    private fun testQuries(){
        PhoneUtil.dial(this, "10086")
    }
}